package org.jeecg.modules.station.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.engineer.entity.MtEngineer;
import org.jeecg.modules.engineer.service.IMtEngineerService;
import org.jeecg.modules.order.service.IMtRepairOrderService;
import org.jeecg.modules.providers.entity.MtServiceProviders;
import org.jeecg.modules.providers.service.IMtServiceProvidersService;
import org.jeecg.modules.station.entity.MtServiceStation;
import org.jeecg.modules.station.service.IMtServiceStationService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 下属服务站
 * @Author: jeecg-boot
 * @Date: 2022-08-08
 * @Version: V1.0
 */
@Api(tags = "下属服务站")
@RestController
@RequestMapping("/station/mtServiceStation")
@Slf4j
public class MtServiceStationController extends JeecgController<MtServiceStation, IMtServiceStationService> {
    @Autowired
    private IMtServiceStationService mtServiceStationService;
    @Autowired
    private IMtServiceProvidersService mtServiceProvidersService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMtEngineerService mtEngineerService;
    @Autowired
    private IMtRepairOrderService mtRepairOrderService;

    /**
     * 分页列表查询
     *
     * @param mtServiceStation
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "下属服务站-分页列表查询")
    @ApiOperation(value = "下属服务站-分页列表查询", notes = "下属服务站-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "station/MtServiceStationList")
    public Result<IPage<MtServiceStation>> queryPageList(MtServiceStation mtServiceStation,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        QueryWrapper<MtServiceStation> queryWrapper = QueryGenerator.initQueryWrapper(mtServiceStation, req.getParameterMap());
        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 平台管理员
        if (sysUser.getUserType() == 0) {
            Page<MtServiceStation> page = new Page<>(pageNo, pageSize);
            IPage<MtServiceStation> pageList = mtServiceStationService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
        // 用户为服务商,根据账号获取服务站
        else if (sysUser.getUserType() == 1) {
            MtServiceProviders providers = mtServiceProvidersService.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, loginUser.getUsername()));
            if (Objects.isNull(providers)) {
                return Result.error("无该服务商信息");
            }
            queryWrapper.lambda().eq(MtServiceStation::getProviderId, providers.getId());
        }
        // 用户为工作站时,根据账号获取工作站下属工程师
        else if (sysUser.getUserType() == 2) {
            MtServiceStation station = mtServiceStationService.getOne(new LambdaQueryWrapper<MtServiceStation>()
                    .eq(MtServiceStation::getUserId, loginUser.getUsername()));
            if (Objects.isNull(station)) {
                return Result.error("无该工作站信息");
            }
            queryWrapper.lambda().eq(MtServiceStation::getId, station.getId());
        }
        // 其他
        else {
            return Result.OK();
        }
        Page<MtServiceStation> page = new Page<MtServiceStation>(pageNo, pageSize);
        IPage<MtServiceStation> pageList = mtServiceStationService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 根据登录用户查询下属服务站（含工程师列表）
     *
     * @param mtServiceStation
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "下属服务站表-根据登录用户查询下属服务站（含工程师列表）", notes = "下属服务站表-根据登录用户查询下属服务站（含工程师列表）")
    @GetMapping(value = "/stationAndEngineerList")
    public Result<IPage<MtServiceStation>> stationAndEngineerList(MtServiceStation mtServiceStation,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                               HttpServletRequest req) {
        QueryWrapper<MtServiceStation> queryWrapper = QueryGenerator.initQueryWrapper(mtServiceStation, req.getParameterMap());
        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 平台管理员
        if (sysUser.getUserType() == 0) {
            Page<MtServiceStation> page = new Page<>(pageNo, pageSize);
            IPage<MtServiceStation> pageList = mtServiceStationService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
        // 用户为服务商,根据账号获取服务商下属工程师
        else if (sysUser.getUserType() == 1) {
            MtServiceProviders providers = mtServiceProvidersService.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, loginUser.getUsername()));
            if (Objects.isNull(providers)) {
                return Result.error("无该服务商信息");
            }
            queryWrapper.lambda().eq(MtServiceStation::getProviderId, providers.getId());
        }
        // 用户为工作站时,根据账号获取工作站下属工程师
        else if (sysUser.getUserType() == 2) {
            MtServiceStation station = mtServiceStationService.getOne(new LambdaQueryWrapper<MtServiceStation>()
                    .eq(MtServiceStation::getUserId, loginUser.getUsername()));
            if (Objects.isNull(station)) {
                return Result.error("无该工作站信息");
            }
            queryWrapper.lambda().eq(MtServiceStation::getId, station.getId());
        }
        // 其他
        else {
            return Result.OK();
        }
        Page<MtServiceStation> page = new Page<>(pageNo, pageSize);
        IPage<MtServiceStation> pageList = mtServiceStationService.page(page, queryWrapper);
        // 获取每个工作站下属工程师
        for (MtServiceStation station : pageList.getRecords()) {
            List<MtEngineer> engineerList = mtEngineerService.list(new LambdaQueryWrapper<MtEngineer>()
                    .eq(MtEngineer::getStationId, station.getId()));
            for (MtEngineer engineer : engineerList) {
                engineer.setOrderNum(mtRepairOrderService.getProcessingListByEngineer(engineer.getId()).size());
            }
            station.setEngineerList(engineerList);
        }
        return Result.OK(pageList);
    }

    /**
     * 通过服务商id查询服务站列表
     *
     * @param providerId
     * @return
     */
    @ApiOperation(value = "通过服务商id查询服务站列表", notes = "通过服务商id查询服务站列表")
    @GetMapping(value = "/listByProviderId")
    public Result<List<MtServiceStation>> queryListByProviderId(@RequestParam(name = "providerId", required = true) String providerId) {
        List<MtServiceStation> mtServiceStationList = mtServiceStationService.list(new LambdaQueryWrapper<MtServiceStation>()
                .eq(MtServiceStation::getProviderId, providerId));
        return Result.OK(mtServiceStationList);
    }

    /**
     * 根据当前登录用户获取服务商区域
     *
     * @param
     * @return
     */
    @ApiOperation(value = "根据当前登录用户获取服务商区域", notes = "根据当前登录用户获取服务商区域")
    @PutMapping(value = "/getAreaByLoginUser")
    public Result getAreaByLoginUser() {
        Object result = mtServiceProvidersService.getAreaByLoginUser();
        return Result.ok(result);
    }

    /**
     * 根据当前登录用户(服务商)获取服务商的服务站列表
     *
     * @param
     * @return
     */
    @ApiOperation(value = "根据当前登录用户(服务商)获取服务商的服务站列表", notes = "根据当前登录用户(服务商)获取服务商的服务站列表")
    @GetMapping(value = "/stationListByLoginUser")
    public Result<List<MtServiceStation>> queryStationListByLoginUser() {
        Object result = mtServiceProvidersService.getProviderIdByLoginUser();
        if (result == null) {
            return Result.error("服务商不存在");
        }
        List<MtServiceStation> mtServiceStationList = mtServiceStationService.list(new LambdaQueryWrapper<MtServiceStation>().eq(MtServiceStation::getProviderId, result.toString()));
        if (mtServiceStationList == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mtServiceStationList);
    }

    /**
     * 根据当前登录的账号 获取服务商ID
     *
     * @param
     * @return
     */
    @ApiOperation(value = "根据当前登录的账号 获取服务商ID", notes = "根据当前登录的账号 获取服务商ID")
    @PutMapping(value = "/getProviderIdByLoginUser")
    public Result getProviderIdByLoginUser() {
        Object result = mtServiceProvidersService.getProviderIdByLoginUser();
        return Result.ok(result);
    }


    /**
     * 添加
     *
     * @param mtServiceStation
     * @return
     */
    @AutoLog(value = "下属服务站-添加")
    @ApiOperation(value = "下属服务站-添加", notes = "下属服务站-添加")
    @RequiresPermissions("station:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MtServiceStation mtServiceStation) {
//		mtServiceStationService.save(mtServiceStation);
        //服务站添加  添加用户 添加部门 关联角色
        mtServiceStationService.saveServiceStationAndCreateUser(mtServiceStation);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mtServiceStation
     * @return
     */
    @AutoLog(value = "下属服务站-编辑")
    @ApiOperation(value = "下属服务站-编辑", notes = "下属服务站-编辑")
    @RequiresPermissions("station:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MtServiceStation mtServiceStation) {
        mtServiceStationService.updateById(mtServiceStation);
        return Result.OK("编辑成功!");
    }

    /**
     * 地图标注
     *
     * @param mtServiceStation
     * @return
     */
    @AutoLog(value = "下属服务站-地图标注")
    @ApiOperation(value = "下属服务站-地图标注", notes = "下属服务站-地图标注")
    @RequiresPermissions("station:coordinate")
    @RequestMapping(value = "/coordinate", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> coordinate(@RequestBody MtServiceStation mtServiceStation) {
        mtServiceStationService.updateById(mtServiceStation);
        return Result.OK("地图标注操作成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "下属服务站-通过id删除")
    @ApiOperation(value = "下属服务站-通过id删除", notes = "下属服务站-通过id删除")
    @RequiresPermissions("station:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        // 校验设备
        mtServiceStationService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "下属服务站-批量删除")
    @ApiOperation(value = "下属服务站-批量删除", notes = "下属服务站-批量删除")
    @RequiresPermissions("station:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mtServiceStationService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "下属服务站-通过id查询")
    @ApiOperation(value = "下属服务站-通过id查询", notes = "下属服务站-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MtServiceStation> queryById(@RequestParam(name = "id", required = true) String id) {
        MtServiceStation mtServiceStation = mtServiceStationService.getById(id);
        if (mtServiceStation == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mtServiceStation);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mtServiceStation
     */
    @RequiresPermissions("station:export")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MtServiceStation mtServiceStation) {
        return super.exportXls(request, mtServiceStation, MtServiceStation.class, "下属服务站");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("station:import")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MtServiceStation.class);
    }

}
